import {
  Tabs,
  Form,
  Input,
  DatePicker,
  Table,
  Space,
  Button,
  Modal,
  message,
} from "antd";
import TextArea from "antd/es/input/TextArea";
import type { ColumnsType } from "antd/es/table";
import { useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import "./index.scss";
import "dayjs/locale/zh-cn";
import http from "../../../utils/http";
import { CSVLink } from "react-csv";
import locale from "antd/es/date-picker/locale/zh_CN";

const Report = () => {
  //时间转换
  const toDub = (n: any) => (n < 10 ? "0" + n : "" + n);
  //年月日时分秒
  const toTime = (date: any) => {
    const oTime = new Date(date);
    return (
      oTime.getFullYear() +
      "-" +
      toDub(oTime.getMonth() + 1) +
      "-" +
      toDub(oTime.getDate()) +
      " " +
      toDub(oTime.getHours()) +
      ":" +
      toDub(oTime.getMinutes()) +
      ":" +
      toDub(oTime.getSeconds())
    );
  };
  //年月日
  const toDate = (date: any) => {
    const oDate = new Date(date);
    return (
      oDate.getFullYear() +
      "-" +
      toDub(oDate.getMonth() + 1) +
      "-" +
      toDub(oDate.getDate())
    );
  };

  //跳转
  const navigate = useNavigate();

  //状态切换
  const onChange = (key: string) => {
    console.log(key);
  };

  // 未解决表格信息
  const [data, setData] = useState([]);
  interface DataType {
    key: string;
    rcontent: String;
    rname: String;
    robject: String;
    rreport: String;
    rtime: String;
    rphone: String;
    rreadytime: String;
  }

  // 表格
  const columns: ColumnsType<DataType> = [
    {
      title: "内容",
      dataIndex: "rcontent",
      key: "rcontent",
      render: (text) => <a className="rcontent">{text}</a>,
    },
    {
      title: "举报人",
      dataIndex: "rname",
      key: "rname",
    },
    {
      title: "举报对象",
      dataIndex: "robject",
      key: "robject",
    },
    {
      title: "提交时间",
      key: "rtime",
      dataIndex: "rtime",
      render: (text) => <a className="rcontent">{toTime(text)}</a>,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              details(record);
            }}
          >
            详情
          </a>
          <a
            onClick={() => {
              solve(record);
            }}
          >
            已解决
          </a>
        </Space>
      ),
    },
  ];

  // 跳转到详情
  const details = (record: any) => {
    navigate("/home/particularstwo", { state: record });
  };

  //渲染未解决数据
  const getData = () => {
    http({
      url: "/getReportOne",
    }).then((res) => {
      console.log("所有数据", res);
      let _data = res.data.map((v: { id: number }) => {
        return { ...v, key: v.id };
      });
      setData(_data);
    });
  };
  useEffect(() => {
    getData();
  }, []);

  //未解决搜索的表单
  const [searchText] = Form.useForm();
  //未解决搜索
  const onSearch = (search: any) => {
    http({
      url: "/searchReportOne",
      params: {
        rname: search.rname || "",
        rtime:
          toDate(search.rtime) == "NaN-NaN-NaN"
            ? ""
            : toDate(search.rtime) || "",
      },
    }).then((res: { [key: string]: any }) => {
      if (res.error == 0) {
        message.success("查询成功");
        let _data = res.data.map((v: { id: number }) => {
          return { ...v, key: v.id };
        });
        setData(_data);
      } else {
        message.error("查询失败");
      }
    });
  };
  //未解决清空搜索
  const clear = () => {
    searchText.resetFields();
    getData();
  };

  // 未解决变已解决
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [passForm] = Form.useForm();
  const solve = (record: any) => {
    passForm.setFieldsValue({ ...record });
    setIsModalOpen(true);
  };
  const handleOk = () => {
    const data1 = passForm.getFieldsValue(true);
    http({
      url: "/passReport",
      method: "post",
      data: {
        id: data1.id,
        rpasstext: data1.rpasstext,
      },
    }).then((res: { [key: string]: any }) => {
      if (res.error == 0) {
        message.success("解决成功");
        setIsModalOpen(false);
        getData();
        getData1();
      } else {
        message.error("解决失败");
      }
    });
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 新增
  const [isAddOpen, setIsAddOpen] = useState(false);
  const showAdd = () => {
    setIsAddOpen(true);
  };
  // 确定新增
  const [addText] = Form.useForm();
  const onAdd = (values: any) => {
    console.log("Add:", values);
    http({
      url: "/addReport",
      method: "post",
      data: {
        rcontent: values.rcontent,
        rname: values.rname,
        rphone: values.rphone,
        robject: values.robject,
      },
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("添加成功");
        setIsAddOpen(false);
        addText.resetFields();
        getData();
      } else {
        message.error("添加失败");
      }
    });
  };
  const handleCancelAdd = () => {
    setIsAddOpen(false);
  };

  //已解决表内容
  const [data1, setData1] = useState([]);
  interface DataType {
    key: string;
    rcontent: String;
    rname: String;
    rphone: String;
    rreport: String;
    rresult: String;
    rreadytime: String;
    rpasstext: String;
  }
  const columns1: ColumnsType<DataType> = [
    {
      title: "内容",
      dataIndex: "rcontent",
      key: "rcontent",
      render: (text) => <a className="rcontent">{text}</a>,
    },
    {
      title: "举报人",
      dataIndex: "rname",
      key: "rname",
    },
    {
      title: "联系电话",
      dataIndex: "rphone",
      key: "rphone",
    },
    {
      title: "举报对象",
      dataIndex: "robject",
      key: "robject",
    },
    {
      title: "解决结果",
      dataIndex: "rpasstext",
      key: "rpasstext",
    },
    {
      title: "解决时间",
      key: "rreadytime",
      dataIndex: "rreadytime",
      render: (text) => <a className="rcontent">{toTime(text)}</a>,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              details1(record);
            }}
          >
            详情
          </a>
        </Space>
      ),
    },
  ];
  // 跳转到详情
  const details1 = (record: any) => {
    navigate("/home/particularstwo1", { state: record });
  };
  //渲染已解决数据
  const getData1 = () => {
    http({
      url: "/getReportTwo",
    }).then((res) => {
      console.log("所有数据", res);
      let _data = res.data.map((v: { id: number }) => {
        return { ...v, key: v.id };
      });
      setData1(_data);
    });
  };
  useEffect(() => {
    getData1();
  }, []);
  //已解决搜索的表单
  const [searchText1] = Form.useForm();
  //已解决搜索
  const onSearch1 = (search: any) => {
    http({
      url: "/searchReportTwo",
      params: {
        rname: search.rname || "",
        rphone: search.rphone || "",
        rreadytime:
          toDate(search.rreadytime) == "NaN-NaN-NaN"
            ? ""
            : toDate(search.rreadytime) || "",
      },
    }).then((res: { [key: string]: any }) => {
      if (res.error == 0) {
        message.success("查询成功");
        let _data = res.data.map((v: { id: number }) => {
          return { ...v, key: v.id };
        });
        setData1(_data);
      } else {
        message.error("查询失败");
      }
    });
  };
  //已解决清空搜索
  const clear1 = () => {
    searchText1.resetFields();
    getData1();
  };

  return (
    <div className="report">
      <div className="title">举报信息</div>
      <div className="hr"></div>

      <Tabs
        defaultActiveKey="1"
        onChange={onChange}
        items={[
          {
            label: `未解决`,
            key: "1",
            children: (
              <>
                <Form
                  name="customized_form_controls"
                  layout="inline"
                  onFinish={onSearch}
                  form={searchText}
                  className="boxBig"
                >
                  <Form.Item name="rname" label="举报人">
                    <Input />
                  </Form.Item>

                  <Form.Item
                    name="rtime"
                    label="提交时间"
                    className="Box_form_date"
                  >
                    <DatePicker locale={locale} placeholder="" />
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" htmlType="submit">
                      查询
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" onClick={clear}>
                      清空查询
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn">
                      <CSVLink data={data} filename="举报信息-未解决导出表.csv">
                        导出结果
                      </CSVLink>
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" onClick={showAdd}>
                      新增
                    </Button>
                  </Form.Item>
                </Form>

                <Table
                  columns={columns}
                  dataSource={data}
                  bordered={true}
                  pagination={{ defaultPageSize: 5 }}
                />

                <Modal
                  title="解决结果"
                  open={isModalOpen}
                  onOk={handleOk}
                  onCancel={handleCancel}
                  okText={"确认"}
                  cancelText={"取消"}
                >
                  <Form form={passForm}>
                    <Form.Item name="rpasstext">
                      <TextArea rows={4} placeholder="请输入解决结果" />
                    </Form.Item>
                  </Form>
                </Modal>

                {/* 新增框 */}
                <Modal
                  title="新增"
                  open={isAddOpen}
                  onCancel={handleCancelAdd}
                  footer={null}
                >
                  <Form
                    form={addText}
                    name="basic"
                    initialValues={{ remember: true }}
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 16 }}
                    autoComplete="off"
                    onFinish={onAdd}
                  >
                    <div className="items">
                      <Form.Item
                        label="举报内容"
                        name="rcontent"
                        style={{ width: 400 }}
                        rules={[
                          {
                            required: true,
                            message: "请填写举报内容!",
                          },
                        ]}
                      >
                        <Input />
                      </Form.Item>

                      <Form.Item
                        label="举报人"
                        style={{ width: 400 }}
                        name="rname"
                        rules={[
                          {
                            required: true,
                            pattern: /^[\u2E80-\u9FFF]+$/,
                            message: "请输入举报人姓名（可匿名）!",
                          },
                        ]}
                      >
                        <Input />
                      </Form.Item>

                      <Form.Item
                        label="联系电话"
                        style={{ width: 400 }}
                        rules={[
                          {
                            required: true,
                            pattern: /^1[3456789]\d{9}$/,
                            message: "请输入正确的联系电话!",
                          },
                        ]}
                        name="rphone"
                      >
                        <Input />
                      </Form.Item>

                      <Form.Item
                        label="举报对象"
                        name="robject"
                        style={{ width: 400 }}
                        rules={[
                          { required: true, message: "请输入你的举报对象!" },
                        ]}
                      >
                        <Input />
                      </Form.Item>
                    </div>

                    <Form.Item wrapperCol={{ offset: 16, span: 16 }}>
                      <Button
                        className="clear"
                        htmlType="button"
                        onClick={handleCancelAdd}
                      >
                        取消
                      </Button>
                      <Button type="primary" htmlType="submit">
                        确定
                      </Button>
                    </Form.Item>
                  </Form>
                </Modal>
              </>
            ),
          },
          {
            label: `已解决`,
            key: "2",
            children: (
              <>
                <Form
                  name="customized_form_controls"
                  layout="inline"
                  onFinish={onSearch1}
                  form={searchText1}
                  className="boxBig"
                >
                  <Form.Item name="rname" label="举报人">
                    <Input />
                  </Form.Item>
                  <Form.Item name="rphone" label="联系方式">
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name="rreadytime"
                    label="解决时间"
                    className="Box_form_date"
                  >
                    <DatePicker locale={locale} placeholder="" />
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" htmlType="submit">
                      查询
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" onClick={clear1}>
                      清空查询
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn">
                      <CSVLink
                        data={data1}
                        filename="举报信息-已解决导出表.csv"
                      >
                        导出结果
                      </CSVLink>
                    </Button>
                  </Form.Item>
                </Form>

                <Table
                  columns={columns1}
                  dataSource={data1}
                  bordered={true}
                  pagination={{ defaultPageSize: 5 }}
                />
              </>
            ),
          },
        ]}
      />
    </div>
  );
};
export default Report;
